/*
 *Copyright © 2015 zhaorongbao
 *招融宝
 *http://zhaorongbao.com
 *All rights reserved.
 */
package com.hanhai.common.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.hanhai.common.exception.BizException;
import com.hanhai.common.util.CommonUtil;

public class MyExceptionHandler implements HandlerExceptionResolver {

	private static final Logger logger = LoggerFactory
			.getLogger(MyExceptionHandler.class);

	private static final String BERROR = "berror";

	private String exceptionPage = "/error/500";

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		logger.error("error", ex);
		ModelAndView view = new ModelAndView(exceptionPage);
		String message = ex.getMessage();
		view.addObject("err", message);
		view.addObject("code", 0);
		if (ex instanceof BizException) {
			view.addObject("errtype", 1);	
			// TODO 硬编码
			if (StringUtils.isNotBlank(message)) {
				view.addObject("msg", message);
			} else {
				view.addObject("msg", ((BizException) ex).getCode());
			}
		} else {
			view.addObject("errtype", 0);
		}
		if (CommonUtil.isAjaxRequest(request)) {
			response.setHeader(BERROR, "yes");  
             CommonUtil.jsonError(response);
             return null;
		}
		return view;
	}

	public String getExceptionPage() {
		return exceptionPage;
	}

	public void setExceptionPage(String exceptionPage) {
		this.exceptionPage = exceptionPage;
	}

}
